#include "ff.h"
#include <errno.h>
#undef errno

extern int errno;

void _exit(int status)
{
    // TODO Anything better than this.
    while (1);
}

static FIL file;

int _open(const char *fn, int flag, ...)
{
	return f_open(&file, fn, FA_READ) == FR_OK ? 0 : -1;
}

int _read(int fil, char * buf, int sz)
{
	UINT read = 0;
	f_read(&file, buf, (UINT)sz, &read);
	return read;
}

int _write(int file, char *ptr, int len)
{	return 0;
}

int _close(int fid)
{
	return f_close(&file) == FR_OK ? 0 : -1;
}

int _isatty (int file)
{    return 0;}

#include <sys/stat.h>int _fstat(int file, struct stat *st)
{	st->st_mode = S_IFCHR;	return 0; 
}

int _lseek(int feli, int ptr, int dir)
{	return f_lseek(&file, ptr) == FR_OK ? 0 : -1;}

register char * stack_ptr asm ("sp");
caddr_t _sbrk (int incr)
{
    extern char _end; /* Defined by the linker */
    static char *heap_end;
    char *prev_heap_end;
    if (heap_end == 0) {
        heap_end = &_end;
    }
    prev_heap_end = heap_end;
    if (heap_end + incr > stack_ptr) {
        errno = EFAULT;
        return (caddr_t) -1;
    }
    heap_end += incr;
    return (caddr_t) prev_heap_end;
}

int _kill(int pid, int sig)
{
    errno = EINVAL;
    return -1;
}

int _getpid (void)
{
    return 1;
}

#include <time.h>
typedef struct timeval TimeVal;
int _gettimeofday (TimeVal * tp, void * tzp)
{
    return 0;
}
